package com.example.design.利用注解加反射消除重复代码.优化;

import com.example.design.利用注解加反射消除重复代码.优化.annotations.BankAPI;
import com.example.design.利用注解加反射消除重复代码.优化.annotations.BankAPIField;
import com.example.design.利用注解加反射消除重复代码.优化.bean.AbstractAPI;
import com.example.design.利用注解加反射消除重复代码.优化.bean.CreateUserAPI;
import com.example.design.利用注解加反射消除重复代码.优化.bean.PayAPI;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @Description TODO
 * @date 2022/12/26 14:29
 * @Author liuzhihui
 * @Version 1.0
 */
@Slf4j
public class BankServiceImpl {


    //创建用户方法
    public static String createUser(String name, String identity, String mobile, int age) throws IOException {
        CreateUserAPI createUserAPI = new CreateUserAPI();
        createUserAPI.setName(name);
        createUserAPI.setIdentity(identity);
        createUserAPI.setAge(age);
        createUserAPI.setMobile(mobile);
        return remoteCall(createUserAPI);
    }
    //支付方法
    public static String pay(long userId, BigDecimal amount) throws IOException {
        PayAPI payAPI = new PayAPI();
        payAPI.setUserId(userId);
        payAPI.setAmount(amount);
        return remoteCall(payAPI);
    }

    private static String remoteCall(AbstractAPI abstractAPI) {
        StringBuilder param = new StringBuilder();
        // 获取所有入参
        Arrays.stream(abstractAPI.getClass().getDeclaredFields())
                // 获取标有BankAPIField注解的字段
                .filter(field -> field.isAnnotationPresent(BankAPIField.class))
                //根据注解中的order对字段排序
                .sorted(Comparator.comparingInt(a -> a.getAnnotation(BankAPIField.class).order()))
                // 设置可以访问私有字段
                .peek(field -> field.setAccessible(true))
                .forEach(field -> {
                    // 获取注解
                    BankAPIField bankAPIField = field.getAnnotation(BankAPIField.class);

                    //反射获取字段值
                    Object value = "";
                    try {
                        value = field.get(abstractAPI);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    //根据字段类型以正确的填充方式格式化字符串
                    switch (bankAPIField.type()) {
                        case "S": {
                            param.append(String.format("%-" + bankAPIField.length() + "s", value.toString()).replace(' ', '_'));
                            break;
                        }
                        case "N": {
                            param.append(String.format("%" + bankAPIField.length() + "s", value.toString()).replace(' ', '0'));
                            break;
                        }
                        case "M": {
                            if (!(value instanceof BigDecimal)) {
                                throw new RuntimeException(String.format("{} 的 {} 必须是BigDecimal", abstractAPI, field));
                            }
                            param.append(String.format("%0" + bankAPIField.length() + "d", ((BigDecimal) value).setScale(2, RoundingMode.DOWN).multiply(new BigDecimal("100")).longValue()));
                            break;
                        }
                        default:
                            break;
                    }
                });

        // 获取接口url
        BankAPI bankAPI = abstractAPI.getClass().getAnnotation(BankAPI.class);

        long begin = System.currentTimeMillis();
//        String result = Request.Post("http://localhost:45678/reflection" + bankAPI.url()) .bodyString(param.toString(), ContentType.APPLICATION_JSON)
//                .execute().returnContent().asString();
        log.info("调用银行API {} url:{} 参数:{} 耗时:{}ms", bankAPI.desc(), bankAPI.url(), param, System.currentTimeMillis() - begin);

        return "";
    }
}
